package wicket.example.providers;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import wicket.example.beans.PatientBean;

public class PatientBeanDataProvider extends SortableDataProvider<PatientBean, String>
{

   private static final long              serialVersionUID = 1L;

   private static final List<PatientBean> list             = new ArrayList<PatientBean>();
   {
      if (list.size() == 0)
      {
    	  for (int i =1; i < 100; i++){
    		  list.add(new PatientBean(String.format("Nick %s", i), String.format("Golubev %s", i), i));
    	  }
      }
   }

   private final DataProviderComparator   COMPARATOR       = new DataProviderComparator();

   
   private transient List<PatientBean> listTest = null;
   
   public PatientBeanDataProvider()
   {
      setSort("name", SortOrder.ASCENDING);
   }

   @Override
   public Iterator<? extends PatientBean> iterator(long first, long count)
   {
      Collections.sort(listTest, COMPARATOR);
      return listTest.subList((int)first, (int)Math.min(first + count, listTest.size())).iterator();
   }

   @Override
   public long size()
   {
      return getData().size();
   }

   private List<PatientBean> getData(){
	   if (listTest == null){
		   listTest = list;
	   }
	   return listTest;
   }
   
   @Override
	public void detach() {
		listTest = null;
	}
   
   @Override
   public IModel<PatientBean> model(PatientBean object)
   {
      return Model.of(object);
   }

   private class DataProviderComparator implements Comparator<PatientBean>, Serializable
   {

      private static final long serialVersionUID = 1L;

      @SuppressWarnings({ "rawtypes", "unchecked" })
      public int compare(final PatientBean o1, final PatientBean o2)
      {
         PropertyModel<Comparable> model1 = new PropertyModel<Comparable>(o1, getSort().getProperty());
         PropertyModel<Comparable> model2 = new PropertyModel<Comparable>(o2, getSort().getProperty());
         int result = model1.getObject().compareTo(model2.getObject());
         if (!getSort().isAscending())
         {
            result = -result;
         }

         return result;
      }

   }

}
